package demo4.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

//@Component
@PropertySource("classpath:config.properties")
public class DBUtil implements IDBUtil{
  //  @Value("${spring.datasource.url}")
    private String url;
   // @Value("${spring.datasource.username}")
    private String username;
  //  @Value("${spring.datasource.password}")
    private String password;
//    static {//静态块想要用配置文件，因为静态块太快了，优先级太高，所以这里就不能这么使用了
//        try {
//            Class.forName("com.mysql.cj.jdbc.Driver");
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        }
//    }

    @Override
    public Connection getConnection() throws SQLException {
       // System.out.println("DBUtil:与数据库进行连接。。。。");
        return DriverManager.getConnection(
                url,
                username,
                password
        );
    }
    @Value("${spring.datasource.url}")
    public void setUrl(String url) {
        this.url = url;
    }
    @Value("${spring.datasource.username}")
    public void setUsername(String username) {
        this.username = username;
    }
    @Value("${spring.datasource.password}")
    public void setPassword(String password) {
        this.password = password;
    }
    @Value("${spring.datasource.classname}")
    public  void  setClassname(String classname){
        try {
            Class.forName(classname);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
